/**
 * 相似需求相关JavaScript
 */

var currentIssueId = null;

/**
 * 打开相似需求模态框
 */
function openSimilarIssuesModal(issueId) {
    currentIssueId = issueId;
    $('#similarIssuesModal').modal('show');
    loadSimilarIssues(issueId);
}

/**
 * 加载相似需求
 */
function loadSimilarIssues(issueId) {
    $('#similarIssuesList').html('<div class="text-center"><i class="fa fa-spinner fa-spin fa-3x"></i><p>正在加载相似需求...</p></div>');
    
    $.ajax({
        url: ctx + 'project/issue/similarity/similar/' + issueId,
        type: 'GET',
        success: function(result) {
            if (result.code == 0) {
                displaySimilarIssues(result.data);
            } else {
                $('#similarIssuesList').html('<div class="alert alert-danger">加载相似需求失败: ' + result.msg + '</div>');
            }
        },
        error: function() {
            $('#similarIssuesList').html('<div class="alert alert-danger">网络错误，加载相似需求失败</div>');
        }
    });
}

/**
 * 基于关键词搜索相似需求
 */
function searchSimilarIssues() {
    var keywords = $('#keywordsInput').val().trim();
    if (!keywords) {
        $.modal.alertWarning('请输入搜索关键词');
        return;
    }
    
    $('#similarIssuesList').html('<div class="text-center"><i class="fa fa-spinner fa-spin fa-3x"></i><p>正在搜索...</p></div>');
    
    $.ajax({
        url: ctx + 'project/issue/similarity/search',
        type: 'GET',
        data: {
            keywords: keywords,
            projectId: $('#projectId').val(),
            limit: 10
        },
        success: function(result) {
            if (result.code == 0) {
                displaySimilarIssues(result.data);
            } else {
                $('#similarIssuesList').html('<div class="alert alert-danger">搜索失败: ' + result.msg + '</div>');
            }
        },
        error: function() {
            $('#similarIssuesList').html('<div class="alert alert-danger">网络错误，搜索失败</div>');
        }
    });
}

/**
 * 显示相似需求列表
 */
function displaySimilarIssues(issues) {
    if (!issues || issues.length === 0) {
        $('#similarIssuesList').html('<div class="alert alert-warning">未找到相似需求</div>');
        return;
    }
    
    var html = '<div class="list-group">';
    
    for (var i = 0; i < issues.length; i++) {
        var issue = issues[i];
        var statusColor = getStatusColor(issue.statusId);
        
        html += '<div class="list-group-item">';
        html += '<div class="row">';
        html += '<div class="col-md-8">';
        html += '<h5>';
        html += '<a href="javascript:void(0);" onclick="openIssueDetail(' + issue.id + ')" class="issue-link">';
        html += '#' + issue.id + ' ' + issue.subject;
        html += '</a>';
        html += '</h5>';
        html += '<p class="text-muted">' + (issue.trackerName || '') + ' | ';
        html += '<span class="label label-' + statusColor + '">' + (issue.statusName || '') + '</span> | ';
        html += '<span class="label label-' + (issue.priority ? issue.priority.listClass : 'default') + '">' + (issue.priorityName || '') + '</span>';
        html += '</p>';
        
        // 显示项目信息
        if (issue.projectName) {
            html += '<p><i class="fa fa-folder-o"></i> ' + issue.projectName;
            if (issue.project && issue.project.customerName) {
                html += ' (' + issue.project.customerName + ')';
            }
            html += '</p>';
        }
        
        // 显示指派人信息
        if (issue.assignedToName) {
            html += '<p><i class="fa fa-user"></i> 指派给: ' + issue.assignedToName + '</p>';
        }
        
        html += '</div>';
        html += '<div class="col-md-4 text-right">';
        html += '<p><small class="text-muted">创建时间: ' + (issue.createTime ? formatDate(issue.createTime) : '') + '</small></p>';
        html += '<p><small class="text-muted">更新时间: ' + (issue.updateTime ? formatDate(issue.updateTime) : '') + '</small></p>';
        html += '<button class="btn btn-sm btn-info" onclick="viewIssueDetails(' + issue.id + ')">';
        html += '<i class="fa fa-eye"></i> 查看详情';
        html += '</button>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    }
    
    html += '</div>';
    $('#similarIssuesList').html(html);
}

/**
 * 计算需求相似度
 */
function calculateSimilarities() {
    if (!currentIssueId) {
        return;
    }
    
    layer.load(2);
    
    $.ajax({
        url: ctx + 'project/issue/similarity/calculate/' + currentIssueId,
        type: 'POST',
        success: function(result) {
            layer.closeAll();
            if (result.code == 0) {
                layer.msg('相似度计算成功', {icon: 1});
                // 重新加载相似需求
                loadSimilarIssues(currentIssueId);
            } else {
                layer.msg('相似度计算失败: ' + result.msg, {icon: 2});
            }
        },
        error: function() {
            layer.closeAll();
            layer.msg('网络错误，相似度计算失败', {icon: 2});
        }
    });
}

/**
 * 打开需求详情
 */
function openIssueDetail(issueId) {
    // 关闭当前模态框
    $('#similarIssuesModal').modal('hide');
    // 打开需求详情页
    $.modal.openTab('需求详情 #' + issueId, ctx + 'project/issue/' + issueId);
}

/**
 * 查看需求详情（不关闭当前模态框）
 */
function viewIssueDetails(issueId) {
    $.ajax({
        url: ctx + 'project/issue/detail/' + issueId,
        type: 'GET',
        success: function(result) {
            if (result.code == 0) {
                // 显示需求详情的简化版本
                showIssueDetailsInModal(result.data);
            } else {
                layer.msg('获取需求详情失败: ' + result.msg, {icon: 2});
            }
        },
        error: function() {
            layer.msg('网络错误，获取需求详情失败', {icon: 2});
        }
    });
}

/**
 * 在模态框中显示需求详情
 */
function showIssueDetailsInModal(issueData) {
    var html = '<div class="panel panel-default">';
    html += '<div class="panel-heading">';
    html += '<h4 class="panel-title">#' + issueData.id + ' ' + issueData.subject + '</h4>';
    html += '</div>';
    html += '<div class="panel-body">';
    
    // 基本信息
    html += '<div class="row">';
    html += '<div class="col-md-6"><strong>状态:</strong> ' + issueData.statusName + '</div>';
    html += '<div class="col-md-6"><strong>优先级:</strong> ' + issueData.priorityName + '</div>';
    html += '</div>';
    
    html += '<div class="row">';
    html += '<div class="col-md-6"><strong>创建者:</strong> ' + issueData.authorName + '</div>';
    html += '<div class="col-md-6"><strong>指派给:</strong> ' + (issueData.assignedToName || '未指派') + '</div>';
    html += '</div>';
    
    html += '<div class="row">';
    html += '<div class="col-md-6"><strong>创建时间:</strong> ' + formatDate(issueData.createTime) + '</div>';
    html += '<div class="col-md-6"><strong>更新时间:</strong> ' + formatDate(issueData.updateTime) + '</div>';
    html += '</div>';
    
    // 描述
    if (issueData.description) {
        html += '<hr><div><strong>描述:</strong></div>';
        html += '<div style="max-height: 200px; overflow-y: auto;">' + issueData.description + '</div>';
    }
    
    html += '</div>';
    html += '</div>';
    
    // 显示详情
    layer.open({
        type: 1,
        title: '需求详情',
        area: ['800px', '600px'],
        content: html
    });
}

/**
 * 获取状态颜色
 */
function getStatusColor(statusId) {
    var colorMap = {
        1: 'primary',    // 新建
        2: 'info',       // 进行中
        3: 'warning',    // 待测试
        4: 'success',    // 已解决
        5: 'danger',     // 反馈
        6: 'default',    // 已关闭
        7: 'warning'     // 重新打开
    };
    return colorMap[statusId] || 'default';
}

/**
 * 格式化日期
 */
function formatDate(dateStr) {
    if (!dateStr) return '';
    
    var date = new Date(dateStr);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    
    return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
}